package com.tec.security.utils.response.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotRoleException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.tec.security.utils.response.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.xml.bind.ValidationException;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final String PACKAGE_NAME = "com.tec.security";

    @ExceptionHandler({NotLoginException.class, NotRoleException.class})
    public Result unauthorized(Exception e) {
        return Result.failure("无权访问",null);
    }

    /**
     * 校验传参
     */
    @ExceptionHandler(ValidationException.class)
    public Result handleBadRequest(Exception e) {
        return Result.failure("数据传递错误",null);
    }

    /**
     * 全局异常处理
     */
    @ExceptionHandler(Exception.class)
    public Result exception(Exception e) {
        return Result.failure("服务器错误",null);
    }

    /**
     * 异常信息处理主体方法
     *
     * @param e 异常对象
     * @return 异常解析信息
     */
    private String e(Exception e) {
        ByteArrayOutputStream printStackTrace = new ByteArrayOutputStream();
        e.printStackTrace(new PrintStream(printStackTrace));
        StringBuilder errorMessage = new StringBuilder();
        errorMessage.append(e);
        if (StringUtils.isBlank(e.getMessage())) {
            return String.valueOf(errorMessage);
        }
        StackTraceElement[] stackTrace = e.getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            String className = stackTraceElement.getClassName();
            if (className.startsWith(PACKAGE_NAME)) {
                String errorName = ";" + stackTraceElement.getClassName();
                errorMessage.append(errorName);
                String errorLineNumber = ":" + stackTraceElement.getLineNumber();
                errorMessage.append(errorLineNumber);
                return String.valueOf(errorMessage);
            }
        }
        return String.valueOf(errorMessage);
    }
}

